package functions.images;

import java.awt.Container;
import java.awt.Graphics2D;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;


// Many thanks to http://kalanir.blogspot.com/2010/02/how-to-split-image-into-chunks-java.html
// for publishing the algorithm for splitting the image.

@SuppressWarnings("serial")
public class ImageSplitTest extends JFrame implements ActionListener{
	
	private static ImageSplitTest frame;
	GridLayout layout = new GridLayout();
	static BufferedImage imgs[];
	static String pictureName = "bear";
	static int n = 7;
	static int shuffles = 1000000;
	
	public ImageSplitTest(String name){
		super(name);
		setResizable(true);
	}
	
    public static void main(String[] args) throws IOException {

        File file = new File(pictureName + ".jpg");
        FileInputStream fis = new FileInputStream(file);
        BufferedImage image = ImageIO.read(fis); //reading the image file

        int rows = n; //You should decide the values for rows and cols variables
        int cols = n;
        int chunks = rows * cols;

        System.out.println("width = " + image.getWidth() + "; heigh = " + image.getHeight());
        
        int chunkWidth = image.getWidth() / cols; // determines the chunk width and height
        int chunkHeight = image.getHeight() / rows;
        int count = 0;
        imgs = new BufferedImage[chunks]; //Image array to hold image chunks
        for (int x = 0; x < rows; x++) {
            for (int y = 0; y < cols; y++) {
            	if(x == rows-1 && y == cols-1){
            		continue;
            	}
                //Initialize the image array with image chunks
                imgs[count] = new BufferedImage(chunkWidth, chunkHeight, image.getType());

                // draws the image chunk
                Graphics2D gr = imgs[count++].createGraphics();
                gr.drawImage(image, 0, 0, chunkWidth, chunkHeight, chunkWidth * y, chunkHeight * x, chunkWidth * y + chunkWidth, chunkHeight * x + chunkHeight, null);
                gr.dispose();
            }
        }
        System.out.println("Splitting done");
        
        file = new File("empty_tile.jpg");
        fis = new FileInputStream(file);
        image = ImageIO.read(fis);
        image = ImageResizer.resizeTrick(image, chunkWidth, chunkHeight);
        imgs[imgs.length - 1] = image;

        //writing mini images into image files
        /*for (int i = 0; i < imgs.length; i++) {
            ImageIO.write(imgs[i], "jpg", new File("img" + i + ".jpg"));
        }
        System.out.println("Mini images created");
        */
        
        /* Use an appropriate Look and Feel */
		try {
			// UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
			UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");
		} catch (UnsupportedLookAndFeelException ex) {
			ex.printStackTrace();
		} catch (IllegalAccessException ex) {
			ex.printStackTrace();
		} catch (InstantiationException ex) {
			ex.printStackTrace();
		} catch (ClassNotFoundException ex) {
			ex.printStackTrace();
		}
		/* Turn off metal's use of bold fonts */
		UIManager.put("swing.boldMetal", Boolean.FALSE);

		// Schedule a job for the event dispatch thread:
		// creating and showing this application's GUI.
		javax.swing.SwingUtilities.invokeLater(new Runnable() {
			public void run() {
				createAndShowGUI();
			}
		});
    }
    
    public void addComponentsToPane(final Container pane){
    	layout = new GridLayout(n,n);
    	
    	final JPanel panel = new JPanel();
    	panel.setLayout(layout);
    	//File file;
    	//FileInputStream fis;
    	//BufferedImage image = null;
    	JLabel picLabel;
    	int[] arr = AlgorithmsForCloudProject.generateShuffledPuzzle_v2(n, shuffles);
    	
    	for(int i = 0; i < n*n; ++i){
    		//file = new File("img" + arr[i] + ".jpg");
    		/*try {
				//fis = new FileInputStream(file);
	    		image = ImageIO.read(file);
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}*/
    		picLabel = new JLabel(new ImageIcon(imgs[arr[i]]));
    		panel.add(picLabel);
    	}
    	pane.add(panel);
    }
    
    private static void createAndShowGUI() {
		// Create and set up the window.
		frame = new ImageSplitTest("MineSweeper, huzzah!");
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		// Set up the content pane.
		frame.addComponentsToPane(frame.getContentPane());
		// Display the window.
		//frame.setBounds(0, 0, 500, 500);
		frame.pack();
		frame.setVisible(true);
	}

	@Override
	public void actionPerformed(ActionEvent arg0) {
		
	}
}
